<?php


namespace app\model;


use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use \Exception as E;

class FloorModel
{
    private static $_table = 'eb_floor'; // 楼层表
    private static $_schoolTable = 'eb_school'; // 学校表
    private static $_dormitoryTable = 'eb_dormitory'; // 宿舍表
    private static $_userTable = 'eb_user'; // 用户
    private static $_floorConfTable = 'eb_floor_conf'; // 楼层配送费配置
    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [
                ['f.operate_id', '=', $adminInfo['id']],
                ['f.school_id', '=', $input['school_id']],
                ['f.dormitory_id', '=', $input['dormitory_id']],
            ];
            if ($input['name'] != '') $map[] = ['f.name', 'like', "%{$input['name']}%"];
            $field = 'f.id,f.name,u.name as username,user_id,   FROM_UNIXTIME(f.create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_table)->alias('f')
                ->leftJoin([self::$_userTable => 'u'], 'u.id = f.user_id')
//                ->leftJoin([self::$_floorConfTable => 'fc'], 'fc.id = f.floor_conf_id')
                ->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $list]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加
     * @param $input
     * @param $token
     * @return Json
     */
    public static function add($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $time = time();
            $input['create_time'] = $time;
            $input['operate_id'] = $admin['id'];
            $input['user_id'] = 0;
            $map = [
                ['id', '=', $input['school_id']],
                ['operate_id', '=', $admin['id']]
            ];
            $sql1 = Db::table(self::$_schoolTable)->field('id')->where($map)->fetchSql(true)->find();
            $map = [
                ['id', '=', $input['dormitory_id']],
                ['operate_id', '=', $admin['id']]
            ];
            $sql2 = Db::table(self::$_dormitoryTable)->field('id')->where($map)->fetchSql(true)->find();
            $where = "exists ({$sql1}) and exists ({$sql2})";
            $sql = makeDualSql(self::$_table, $input, $where);
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->execute($sql);
            if ($rtn) {
                //添加缓存
                $dorInfo = Cache::store('redis')->handler()->hGet('dxsd-school-' . $input['school_id'], 'dormitory-' . $input['dormitory_id']);
                if (!$dorInfo) {
                    Db::rollback();
                    return jsonFail('获取宿舍楼信息失败');
                }
                $map = [
                    ['create_time', '=', $time]
                ];
                $floorId = Db::table(self::$_table)->field('id')->where($map)->find();
                if (!$floorId) {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
                $dorInfo = json_decode($dorInfo, true);
                $dorInfo['floor-' . $floorId['id']] = [
                    'name' => $input['name']
                ];
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $input['school_id'], 'dormitory-' . $input['dormitory_id'], json_encode($dorInfo));
                if ($addRtn === 0) {
                    Db::commit();
                    return jsonSuccess('添加成功！');
                } else {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('该学校名已使用，添加失败！');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**删除
     * @param $input
     * @param $token
     * @return Json
     */
    public static function delete($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['id', '=', $input['id']];
            $map[] = ['operate_id', '=', $admin['id']];
            $map[] = ['school_id', '=', $input['school_id']];
            $map[] = ['dormitory_id', '=', $input['dormitory_id']];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->delete();
            if ($rtn) {
                // 删除缓存
                $dorInfo = Cache::store('redis')->handler()->hGet('dxsd-school-' . $input['school_id'], 'dormitory-' . $input['dormitory_id']);
                if (!$dorInfo) {
                    Db::rollback();
                    return jsonFail('获取宿舍楼信息失败');
                }
                $dorInfo = json_decode($dorInfo, true);
                unset($dorInfo['floor-' . $input['id']]);
                $delRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $input['school_id'], 'dormitory-' . $input['dormitory_id'], json_encode($dorInfo));
                if ($delRtn === 0) {
                    Db::commit();
                    return jsonSuccess('删除成功！');
                } else {
                    Db::rollback();
                    return jsonFail('删除失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('未找到数据或者存在未删除的楼层，请先刷新确认');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getOnly($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
//            $confInfo = FloorConfModel::getSimpleStatic($admin['id'], $input['school_id']);
//            if (!is_array($confInfo)) return $confInfo;
            $map[] = ['id', '=', $input['id']];
            $map[] = ['operate_id', '=', $admin['id']];
            $map[] = ['school_id', '=', $input['school_id']];
            $map[] = ['dormitory_id', '=', $input['dormitory_id']];
            $rtn = Db::table(self::$_table)->field('id, name,school_id,dormitory_id,floor_conf_id')->where($map)->find();
            if ($rtn) return jsonSuccess('获取成功', ['info' => $rtn]);
            return jsonFail('获取失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑
     * @param $input
     * @param $token
     * @return Json
     */
    public static function edit($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['id', '=', $input['id']];
            $map[] = ['operate_id', '=', $admin['id']];
            $map[] = ['school_id', '=', $input['school_id']];
            $map[] = ['dormitory_id', '=', $input['dormitory_id']];
            $id = $input['id'];
            $schoolId = $input['school_id'];
            $dormitoryId = $input['dormitory_id'];
            unset($input['id']);
            unset($input['school_id']);
            unset($input['dormitory_id']);
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $dorInfo = Cache::store('redis')->handler()->hGet('dxsd-school-' . $schoolId, 'dormitory-' . $dormitoryId);
                if (!$dorInfo) {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
                $dorInfo = json_decode($dorInfo, true);
                $dorInfo['floor-' . $id]['name'] = $input['name'];
                $editRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $schoolId, 'dormitory-' . $dormitoryId, json_encode($dorInfo));
                if ($editRtn === 0) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取未绑定的用户
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getUnbindUser($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [
                ['operate_id', '=', $adminInfo['id']],
                ['school_id', '=', $input['school_id']],
                ['dormitory_id', '=', $input['dormitory_id']],
                ['delivery_floor', '=', 0],
                ['type', '=', 2],
                ['status', '=', 2]
            ];
            if ($input['name'] != '') $map[] = ['name', 'like', "%{$input['name']}%"];
            $field = 'id,name,phone';
            $table = Db::table(self::$_userTable)
                ->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $list]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**绑定用户
     * @param $input
     * @param $token
     * @return Json
     */
    public static function bindUser($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            Db::startTrans();
            $flag = true;
            $map = [
                ['id', '=', $input['user_id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']],
                ['dormitory_id', '=', $input['dormitory_id']],
                ['delivery_floor', '=', 0],
                ['type', '=', 2],
                ['status', '=', 2]
            ];
            $rtn = Db::table(self::$_userTable)->where($map)->update(['delivery_floor' => $input['delivery_floor']]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('绑定失败,请刷新页面重试');
            }
            $map = [
                ['id', '=', $input['delivery_floor']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']],
                ['dormitory_id', '=', $input['dormitory_id']],
                ['user_id', '=', 0]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['user_id' => $input['user_id']]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('绑定失败,请刷新页面重试');
            }
            //修改缓存
            $rtn = Cache::store('redis')->handler()->hSet('dxsd-user-' . $input['user_id'], 'delivery_floor', $input['delivery_floor']);
            if ($rtn !== 1) {
                Db::rollback();
                return jsonFail('绑定失败,请刷新页面重试');
            }
            Db::commit();
            return jsonSuccess('绑定成功');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**解绑用户
     * @param $input
     * @param $token
     * @return Json
     */
    public static function unbindUser($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            Db::startTrans();
            $flag = true;
            $map = [
                ['id', '=', $input['user_id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']],
                ['dormitory_id', '=', $input['dormitory_id']],
                ['delivery_floor', '=', $input['delivery_floor']]
            ];
            $rtn = Db::table(self::$_userTable)->where($map)->update(['delivery_floor' => 0]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('解绑失败,请刷新页面重试');
            }
            $map = [
                ['id', '=', $input['delivery_floor']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']],
                ['dormitory_id', '=', $input['dormitory_id']],
                ['user_id', '=', $input['user_id']]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['user_id' => 0]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('解绑失败,请刷新页面重试');
            }
            //修改缓存
            $rtn = Cache::store('redis')->handler()->hDel('dxsd-user-' . $input['user_id'], 'delivery_floor');
            if ($rtn !== 1) {
                Db::rollback();
                return jsonFail('绑定失败,请刷新页面重试');
            }
            Db::commit();
            return jsonSuccess('解绑成功');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
}